<template>
    <!-- style="margin-top:1rem" -->
    <a-row>
        <NoAuthPage v-showNoAuth="'D16-1'" :imgBoxStyle="{ height: '40vh', margin: '0 10px 10px' }" />

        <a-col :xs='24' :sm='24' :md='24' :lg='24' :xl='24' :xxl='24' v-userAuth="'D16-1'">
            <div style="margin:0 0 1em 0 ">
                <a-button type="primary" @click="create = true" v-userAuth="'D16-2'">
                    <!-- <i class="icon icon-new16f button-icon-style"></i> -->

                    <Iconfont class="icon button-icon-style" type="icon-new16f"></Iconfont>
                    {{ $t('Create') }}

                </a-button>
                <!-- <a-tooltip placement='bottom' v-userAuth="'D16-2'">
		          	<template slot='title'>
		            	<span>{{$t('Create')}}</span>
		          	</template>
<a-button type="primary" @click="create = true">
    icon='file-add'
    <i class="icon icon-new16f"></i>
</a-button>
</a-tooltip>
-->
                <!-- <a-tooltip placement='bottom' v-userAuth="'D16-3'">
		            <template slot='title'>
		                <span>{{$t('Edit')}}</span>
		            </template>
		        	<a-button :disabled="selectedRowKeys.length==0" type='primary' style="margin-left:1em" @click="openmodal('edit')">
                        icon='form'
                        <i class="icon icon-edit16f"></i>
                    </a-button>
		        </a-tooltip> -->
                <!-- <a-tooltip placement='bottom' v-userAuth="'D16-4'">
		            <template slot='title'>
		                <span>{{$t('Delete')}}</span>
		            </template>
		            <a-button :disabled="selectedRowKeys.length==0" type='danger' style="margin-left:1em" @click="openmodal('del')">
                        icon='close-circle'
                        <i class="icon icon-error16f"></i>
                    </a-button>
		        </a-tooltip> -->
            </div>
            <div class="bigstyle">
                <a-table class="bigtab" rowKey="id" :columns='bucketcolumns' :loading="loading" :dataSource='bucketdata'
                :components="tableComponents" :locale="defaultSetting" size='small' :pagination="false">
                    <!-- :rowSelection='{type:"radio",selectedRowKeys:selectedRowKeys,onChange:onSelectChange, onSelect:onSelect}'  -->
                    <span slot="is_enabled" slot-scope='is_enabled'>
                        <span :class="is_enabled == true ? 'green-circle' : 'red-circle'"></span>
                        {{ is_enabled == true ? $t('Active') : $t('Inactivated') }}
                        <!-- <a-tag :color="is_enabled == true?'green':'red'">
                        {{is_enabled == true?$t('Active'):$t('Inactivated')}}
                    </a-tag> -->
                    </span>
                    <div slot="max_size" slot-scope='text, record'>
                        <span v-if="text == -1">{{ $t('Unlimited') }}</span>
                        <span v-else>{{ text }}</span>
                    </div>
                    <div slot="max_objects" slot-scope='text, record'>
                        <span v-if="text == -1">{{ $t('Unlimited') }}</span>
                        <span v-else>{{ text }}</span>
                    </div>
                    <div slot="filterDropdown"
                        slot-scope="{ setSelectedKeys, selectedKeys, confirm, clearFilters, column }"
                        class='custom-filter-dropdown'>
                        <a-input v-ant-ref="c => searchInput = c" :placeholder="$t('Enter') + $t('Search-content')"
                            :value="selectedKeys[0]"
                            @change="e => setSelectedKeys(e.target.value ? [e.target.value] : [])"
                            @pressEnter="() => handleSearch(selectedKeys, confirm)"
                            style="width: 188px; margin-bottom: 8px; display: block;" />
                        <a-button type='primary' @click="() => handleSearch(selectedKeys, confirm)" icon="search"
                            size="small" style="width: 90px; margin-right: 8px">{{ $t('Search') }}
                        </a-button>
                        <a-button @click="() => handleReset(clearFilters)" size="small" style="width: 90px">{{
                            $t('Reset')
                            }}
                        </a-button>
                    </div>
                    <a-icon slot="filterIcon" slot-scope="filtered" type='search'
                        :style="{ color: filtered ? '#108ee9' : undefined }" />
                    <template slot="customRender" slot-scope="text, record">
                        <span v-if='searchText'>
                            <template
                                v-for="(fragment, i) in text.toString().split(new RegExp(`(?<=${searchText})|(?=${searchText})`, 'i'))">
                                <mark v-if="fragment.toLowerCase() === searchText.toLowerCase()" :key="i"
                                    class="highlight jump-text">{{ fragment }}</mark>
                                <template v-else>
                                    <span :key="i" class="jump-text">{{ fragment }}</span>
                                </template>
                            </template>
                        </span>
                        <template v-else>
                            <span class="jump-text">{{ text }}</span>
                        </template>
                    </template>
                    <template slot="used_percent" slot-scope='used_percent, record'>
                        <div v-if="record.max_size == '-1'">-</div>
                        <div v-else>{{ used_percent === 'unknown' ? 'unknown' : used_percent + '%' }}</div>
                    </template>
                    <template slot="operate" slot-scope='text, record'>
                        <a-tooltip placement='top' v-userAuth="'D16-3'">
                            <template slot='title'>
                                <span>{{ $t('Edit') }}</span>
                            </template>
                            <!-- <i class="icon icon-edit16f table-operation-icon" @click="editBucket(record)"></i> -->

                            <Iconfont class="icon table-operation-icon" type="icon-edit16f" @click="editBucket(record)">
                            </Iconfont>
                        </a-tooltip>
                        <a-tooltip placement='top' v-userAuth="'D16-4'">
                            <template slot='title'>
                                <span>{{ $t('Delete') }}</span>
                            </template>
                            <!-- <i class="icon icon-delete16f table-operation-icon" @click="deiBucket(record)"></i> -->

                            <Iconfont class="icon table-operation-icon" type="icon-delete16f"
                                @click="deiBucket(record)">
                            </Iconfont>
                        </a-tooltip>
                    </template>
                </a-table>
                <a-pagination v-model="current" :page-size-options="pageSizeOptions" :total="total"
                    :show-total="total => $store.state.language == 'zh' ? `共 ${total} 条数据` : `A-total-of ${total} data`" show-size-changer :page-size="pageSize"
                    @showSizeChange="handlePageSizeChange" @change="handlePageChange">
                    <template slot="buildOptionText" slot-scope="props">
                        <span>{{ props.value }} {{ $t('条/页') }}</span>
                    </template>
                </a-pagination>
            </div>
        </a-col>
        <!-- 删除桶 -->
        <a-modal :title="$t('Delete') + $t('Bucket')" v-model="delbuk" v-dragModal>
            <a-spin size="large"
                style="position:absolute;left:50%; top:50%; transform: translate(-50%, -50%);z-index:1;background:rgba(255,255,255,.6);padding:10%"
                tip="Submit successfully Loading..." v-if="spinning == true"></a-spin>
            <p v-if="!isShowChecked">{{ $t('Note') }}</p>
            <p v-else>{{ $t('注意：当前桶内，已经存在数据') }}</p>
            <a-form :form='form'>
                <a-form-item v-if="isShowChecked">
                    <a-checkbox :checked="checked" @change="onChange" v-decorator="['purge_data', {
                        rules: [
                            { required: true, message: $t('Please_agree_first') }
                        ]
                    }, { valuePropName: 'checked' }]">
                        {{ $t('Agree') }}：{{ target ? target.name : '' }}
                    </a-checkbox>
                </a-form-item>
                <div v-if="isShowChecked && checked" style="margin-top: -8px;">
                    <span style="color: #C13B52">此操作为危险操作，一旦误删，数据将无法恢复！</span>
                    <span>如您确定要进行操作，请输入以下文字后点击确定。</span>
                    <div class="sure-text">{{ $t('Know-and-continue') }}</div>
                    <a-input v-model="confirmValue" :placeholder="$t('Enter-top-text')"></a-input>
                </div>
                <span v-if="checkedTips" style="color: var(--mainRedColor)">{{ $t('Please_agree_first') }}</span>
            </a-form>
            <template slot="footer">
                <a-button key="back" @click="cancelhandle" >
                    {{ $t('Cancel') }}
                </a-button>
                <a-button v-if="!isShowChecked" type="primary" @click="del">
                    {{ $t('Sure') }}
                </a-button>
                <a-button v-else type="primary" @click="del"
                    :disabled="(confirmValue == '我已知情，确定要继续操作！' || confirmValue == 'I have been informed and am sure to continue!') ? false : true">
                    {{ $t('Sure') }}
                </a-button>
            </template>
        </a-modal>
        <Cbucket :bb='create' @omodal='changemodal' :tarname='areadata' :paramsdata="paramsdata"></Cbucket>
        <Ebucket :ee='edit' @omodal='changemodal' :tarname='onerecord' :areadata='areadata' ref="editBucket"></Ebucket>
    </a-row>
</template>
<script>
import Cbucket from './bucketpro/cbucket'
import Ebucket from './bucketpro/ebucket'
import EmptyData from '@/components/common/EmptyData'
import NoAuthPage from '@/components/common/NoAuthPage'

import request from '@/request/request'

export default {
    name: 'bucket',
    components: { Cbucket, Ebucket, EmptyData, NoAuthPage },
    data() {
        this.tableComponents = {
			header: {
				cell: (h, props, children) => {
					const { key, ...restProps } = props
					// 此处的this.columns 是定义的table的表头属性变量
					const col = this.bucketcolumns.find((col) => {
						const k = col.dataIndex || col.key
						return k === key
					})
					if (!col || !col.width) {
						return h('th', { ...restProps }, [...children])
					}
					const dragProps = {
						key: col.dataIndex || col.key,
						class: 'table-draggable-handle',
						attrs: {
							w: 10,
							x: col.width,
							z: 1,
							axis: 'x',
							draggable: true,
							resizable: false,
						},
						on: {
							dragging: (x, y) => {
								col.width = Math.max(x, 20)
							},
						},
					}
					const drag = h('vue-draggable-resizable', { ...dragProps })
					return h('th', { ...restProps, class: 'resize-table-th' }, [...children, drag])
				}
			}
		}
        return {
            bucketcolumns: [
                {
                    title: this.$t('Bucket') + this.$t('Name'),
                    dataIndex: "name",
                    key: "name",
                    sorter: (a, b) => a.name.length - b.name.length,
                    scopedSlots: {
                        filterDropdown: 'filterDropdown',
                        filterIcon: 'filterIcon',
                        customRender: 'customRender'
                    },
                    onFilter: (value, record) => record.name.toLowerCase().includes(value.toLowerCase()),
                    onFilterDropdownVisibleChange: (visible) => {
                        if (visible) {
                            setTimeout(() => {
                                this.searchInput.focus()
                            }, 0)
                        }
                    },
                    // fixed: 'left',
                    // width: this.$store.state.language == 'zh' ? 120 : 190
                    width: 160,
                    fixed: 'left',
                },
                {
                    title: this.$t('Owner'),
                    dataIndex: "owner",
                    key: "owner",
                    ellipsis: true,
                    sorter: (a, b) => a.owner.length - b.owner.length,
                    scopedSlots: {
                        filterDropdown: 'filterDropdown',
                        filterIcon: 'filterIcon',
                        customRender: 'customRender'
                    },
                    onFilter: (value, record) => record.owner.toLowerCase().includes(value.toLowerCase()),
                    onFilterDropdownVisibleChange: (visible) => {
                        if (visible) {
                            setTimeout(() => {
                                this.searchInput.focus()
                            }, 0)
                        }
                    },
                    // fixed: 'left',
                    width: this.$store.state.language == 'zh' ? 120 : 190
                },
                { title: this.$t('区域组'), dataIndex: 'zonegroup_name', key: 'zonegroup_name', width: 100 },
                { title: this.$t('存储区域'), dataIndex: 'placement', key: 'placement', width: 100 },
                { title: this.$t('Bucket') + this.$t('Quota'), dataIndex: 'is_enabled', key: 'is_enabled', scopedSlots: { customRender: 'is_enabled' }, width: 100 },
                { title: this.$t('对象个数'), dataIndex: 'objects', key: 'objects', sorter: (a, b) => a.objects - b.objects, width: 100 },
                {
                    title: this.$t('已用容量'),
                    dataIndex: 'used',
                    key: 'used',
                    sorter: (a, b) => a.used_bytes - b.used_bytes,
                    width: 100
                },
                { title: this.$t('容量使用率'), dataIndex: 'used_percent', key: 'used_percent', scopedSlots: { customRender: 'used_percent' }, width: 100 },
                { title: this.$t('Max-capacity'), dataIndex: 'max_size', key: 'max_size', scopedSlots: { customRender: 'max_size' }, width: 100 },
                { title: this.$t('Max-obj'), dataIndex: 'max_objects', key: 'max_objects', scopedSlots: { customRender: 'max_objects' } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 140, fixed: 'right', }
                // {title: this.$t('Storage-area'),dataIndex:'placement',key:'placement'}
            ],
            // pagination: {
            //     // defaultPageSize: 5,
            //     // showTotal: total => `${this.$t('A-total-of')} ${total} ${this.$t('Data')}`,
            //     // showSizeChanger: true,
            //     // pageSizeOptions: ['5', '15', '20', '25'],
            //     // onShowSizeChange: onChangePage(current, pageSize),
            //     // buildOptionText: (props) => `${props.value} / ${this.$t('page')}`
            // },
            bucketdata: [
                // {key:'0',name:'asdas',master:'active',per:'nceph2',max:'Reqs:0/s',obj:'10'}
            ],
            form: this.$form.createForm(this),
            formlayout: {
                labelCol: { span: 6 },
                wrapperCol: { span: 14 }
            },
            tailFormItemLayout: {
                wrapperCol: {
                    xs: {
                        span: 24,
                        offset: 0,
                    },
                    sm: {
                        span: 16,
                        offset: 8,
                    },
                },
            },
            basebucket: [],
            selectedRowKeys: [],
            create: false,
            edit: false,
            delbuk: false,
            ids: '',
            onerecord: '',
            spinning: false,
            loading: true,
            areadata: '',
            num: 0,
            checked: false,
            checkedTips: false,
            target: '',
            defaultSetting: { emptyText: <EmptyData /> },
            searchText: '',
            // 是否显示删除桶的勾选选项
            isShowChecked: false,
            confirmValue: '',
            paramsdata: [],
            pageSizeOptions: ['5', '10', '20', '50'],
            current: 1,  // 当前页
            pageSize: 10,  // 每页显示条数
            total: 0,

        }
    },
    mounted() {
        this.getdata(this.current, this.pageSize)
        this.getbasedata()
        this.getParamsData()
    },
    computed: {
        getbasebucket() {
            return this.$store.state.basebucket
        },
        getlanguage() {
            return this.$store.state.language
        }
    },
    watch: {
        getlanguage(val) {
            this.bucketcolumns = [
                { title: this.$t('Bucket') + this.$t('Name'), dataIndex: 'name', key: 'name', sorter: (a, b) => a.name.length - b.name.length },
                { title: this.$t('Owner'), dataIndex: 'owner', key: 'owner' },
                { title: this.$t('Bucket') + this.$t('Quota'), dataIndex: 'is_enabled', key: 'is_enabled', scopedSlots: { customRender: 'is_enabled' } },
                { title: this.$t('Max-capacity'), dataIndex: 'max_size', key: 'max_size', scopedSlots: { customRender: 'max_size' } },
                { title: this.$t('Max-obj'), dataIndex: 'max_objects', key: 'max_objects', scopedSlots: { customRender: 'max_objects' } },
                { title: this.$t('Operate'), key: "operate", scopedSlots: { customRender: 'operate' }, width: 120 }
                // {title: this.$t('Storage-area'),dataIndex:'placement',key:'placement'}
            ]
        },
        "$store.state.isUpdateUserList"(newValue) {
            if (newValue) {
                this.getbasedata();
                this.$store.commit('toUpdateUsers', false);
            }
        }
    },
    methods: {
        handlePageSizeChange(current, pageSize) {
            this.pageSize = pageSize;
            this.getdata(current, pageSize);  // 调用 fetchData 获取数据
        },
        handlePageChange(page) {
            this.current = page;
            this.getdata(page, this.pageSize);  // 调用 fetchData 获取数据
        },
        getdata(page, pageSize) {
            this.loading = true
            const params = {
                page: page,
                page_size: pageSize
            }
            request('get', 'rgw/v2/bucket/', params).then(res => {
                // console.log('桶列表', res)
                if (res.data.flag == 1) {
                    this.model(res.data.id) //返回模板
                    this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
                } else {
                    if (res.status == 200) {
                        this.bucketdata = res.data.bucket_infos
                        this.total = res.data.count
                        if (this.bucketdata.length !== 0) {
                            this.onerecord = this.bucketdata[this.num]
                        }
                    }
                }
                // if(res.data.flag == 1) {
                //     if(Object.keys(res.data.params).length == 0) {
                //         this.$message.error(this.$t('Unknown-error'));
                //     }else {
                //         this.$message.error(res.data.params.detail);
                //     }
                //     this.loading = false;
                // }else {
                //     // for(var i=0;i<res.data.length;i++){
                //     //     // res.data[i].is_enabled = res.data[i].is_enabled.toString()
                //     //     if(res.data[i].max_size == -1){
                //     //         res.data[i].max_size = '∞'
                //     //     }else{
                //     //         // res.data[i].max_size = this.bytesToSize(res.data[i].max_size)
                //     //     }
                //     //     if(res.data[i].max_objects == -1){
                //     //         res.data[i].max_objects = '∞'
                //     //     }
                //     // }

                // }
            }).catch(err => {

            }).finally(() => {
                this.loading = false;
            })
            // setTimeout(() => {
            //     this.bucketdata.push({
            //     id: "0a218704-bf58-4374-8ebb-ab9d8ab693b7.2",
            //     name: "bbb",
            //     is_enabled: true,
            //     max_objects: "213",
            //     max_size: -1,
            //     owner: "bbb",
            //     placement: "default-placement",
            //     used: "0 B",
            //     objects: "1",
            //     used_percent: "unknown"
            // })
            // }, 1000)
        },
        // onChangePage(current, pageSize) {
        //     this.page = current
        //     this.pageSize = pageSize
        //     this.getdata()
        // },


        getParamsData() {
            request('get', '/rgw/v2/bucket/create_args/').then(res => {
                console.log("getdaa", res)
                this.paramsdata = res.data
                console.log("get", this.paramsdata)
            })

        },

        getbasedata() {
            // this.$axios.get(this.allurl+'rgw/bucket/_info').then(res=>{
            request('post', 'rgw/user/getNameAll').then(res => {
                // console.log('获取所有者', res)
                if (res.data.flag == 1) {
                    this.$message.error(res.data.params.detail);
                    this.$store.commit('getbasebucket', {
                        basebucket: [],
                    })
                } else {
                    this.$store.commit('getbasebucket', {
                        basebucket: res.data,
                    })
                }
                //暂时注释，换了接口，新接口只有所有者 for(var i=0;i<res.data.zone.length;i++){
                //     if(res.data.zone[i].id == 'default-placement'){
                //         this.areadata = res.data.zone[i]
                //     }
                // }
            })
        },
        onSelect(record, selected, selectedRows) {
            for (let i = 0; i < this.bucketdata.length; i++) {
                if (this.bucketdata[i].name == record.name) {
                    this.target = record
                    this.ids = this.bucketdata[i].id
                    this.onerecord = this.bucketdata[i]
                    this.num = i
                }
            }
        },
        onSelectChange(selectedRowKeys) {
            // if(selectedRowKeys.length!=0){
            // 	this.target = this.bucketdata[selectedRowKeys].name
            // }
            this.selectedRowKeys = selectedRowKeys
        },
        editBucket(record) {
            for (let i = 0; i < this.bucketdata.length; i++) {
                if (this.bucketdata[i].name == record.name) {
                    this.target = record;
                    this.ids = this.bucketdata[i].id
                    this.onerecord = this.bucketdata[i]
                    this.num = i
                }
            }
            this.edit = true;
            if (record.owner == 'admin') this.$refs.editBucket.isAdmin = false
            else this.$refs.editBucket.isAdmin = true
        },
        openmodal(name) {
            if (this.selectedRowKeys.length != 0) {
                if (name == 'del') {
                    this.delbuk = true
                } else if (name == 'edit') {
                    this.edit = true
                }
            }
            else {
                this.$notification['error']({
                    message: this.$t('Choose') + this.$t('Operating-object')
                })
            }
        },
        // del(){
        //     let _this = this
        // 	this.$confirm({
        //         title:this.$t('Delete')+this.$t('Bucket'),
        //         content:'你确定删除所选中的桶 '+this.target+' 吗？',
        //         cancelText:this.$t('Cancel'),
        // 		okText:this.$t('Sure'),
        //         okType:'danger',
        //         onOk(){
        //             _this.$axios.delete(_this.allurl+'rgw/bucket',{
        //                 data:{
        //                     id:_this.ids
        //                 }
        //             }).then(res=>{
        //                 _this.model(res.data.id) //返回模板
        //                 _this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示
        // 				_this.gettask()  //任务栏信息
        //                 _this.getdata()
        //             })
        //         },
        //         onCancel(){
        //         }
        //     })
        // },
        deiBucket(record) {
            this.target = record;
            this.delbuk = true;
            if (record.objects == '0') {
                this.isShowChecked = false
            } else {
                this.isShowChecked = true
            }
        },
        //删除桶
        del(e) {
            e.preventDefault();
            this.form.validateFields((err, value) => {
                if (!err) {
                    if (this.checked || !this.isShowChecked) {
                        this.spinning = true
                        request('DELETE', 'rgw/bucket', {
                            // data:{
                            // id:this.ids,
                            // purge_data:value.purge_data
                            name: this.target.name,
                            confirm: this.checked,
                            // }
                        }).then(async res => {
                            this.model(res.data.id) //返回模板
                            this.notice(res.data.id, res.data.params, res.data.flag) //通知列表显示                            
                            // this.gettask()  //任务栏信息
                            // this.getdata()
                            this.spinning = false
                            this.form.resetFields();
                            this.delbuk = false
                            this.checked = false
                            this.selectedRowKeys = []; // 将选择的项清空
                            let state
                            let timer = setInterval(async () => {
                                const { data } = await request('put', 'logmanage/background_task/recent', {
                                    page_size: 10
                                })
                                state = data[0].state
                                this.getdata(this.current, this.pageSize)
                                if (state == '1') {
                                    clearInterval(timer)
                                }
                            }, 1000)
                        })
                    } else {
                        this.checkedTips = true
                    }
                }
            })
        },
        onChange(checkedValues) {
            this.checked = !this.checked
        },
        changemodal(val, isCancel) {
            this.edit = val
            this.create = val
            if (!isCancel) {
                this.getdata(this.current, this.pageSize);
            }
            this.checked = false
        },
        cancelhandle() {
            this.form.resetFields();
            this.delbuk = false
        },
        handleSearch(selectedKeys, confirm) {
            confirm()
            this.searchText = selectedKeys[0]
        },
        handleReset(clearFilters) {
            clearFilters()
            this.searchText = ''
        },
        handleCreate() {
            this.create = true
            this.$refs.editBucket.isAdmin = false
        }
    }
}
</script>

<style scoped>
.sure-text {
    text-align: center;
    color: var(--mainRedColor);
    font-weight: 700;
    padding: 4px 0;
    background-color: rgba(253, 52, 85, 0.1);
    border-left: 2px solid var(--mainRedColor);
    margin: 15px 0 10px;
}

:deep(.ant-pagination) {
    float: right;
    margin: 16px;
}

::v-deep.bigtab .table-draggable-handle {
	/* width: 10px !important; */
	height: 100% !important;
	left: auto !important;
	right: -5px;
	cursor: col-resize;
	touch-action: none;
	border: none;
	position: absolute;
	transform: none !important;
	bottom: 0;
}

::v-deep.bigtab .resize-table-th {
	position: relative;
}
</style>
